package ms.unicorn.dsl.runtime.interpreter;

import ms.unicorn.dsl.runtime.ExecutionContext;
import ms.unicorn.dsl.runtime.SphynxInterpreter;
import ms.unicorn.dsl.runtime.VariableStorage;
import ms.unicorn.dsl.unicornDSL.XExpression;
import ms.unicorn.dsl.unicornDSL.XFunctionDeclaration;
import ms.unicorn.dsl.unicornDSL.XReturnStatement;
import ms.unicorn.dsl.unicornDSL.impl.XBlockExpressionImpl;
import ms.unicorn.dsl.unicornDSL.impl.XFunctionDeclarationImpl;
import ms.unicorn.dsl.unicornDSL.impl.XReturnStatementImpl;


public class XFunctionDeclartationInterpreter {
	
	public static Object _evaluate(SphynxInterpreter interpreter, XFunctionDeclarationImpl funcDef, ExecutionContext context) {
		return funcDef;
	}
	
	/*public static Object _evaluate(SphynxInterpreter interpreter, XPatternDeclarationImpl funcDef, ExecutionContext context) {
		return funcDef;
	}*/
		
	public static Object _evaluate(SphynxInterpreter interpreter, XBlockExpressionImpl block, ExecutionContext context) {
		Object result = null;
		for(XExpression exp: block.getExpressions()) {			
			result = interpreter.evaluate(exp, context);
			if (result instanceof XReturnStatement)
				break;			
		}
		return result;
	}
	
	public static Object _evaluate(SphynxInterpreter interpreter, XReturnStatementImpl res, ExecutionContext context) {
		return res;
	}
	
	public static Object interpret(SphynxInterpreter interpreter, XFunctionDeclaration funcDef, ExecutionContext context) {
		// parameter passing is done by caller
		context.setExecutingFunction(funcDef);
		Object obj = interpreter.evaluate(funcDef.getBody(), context);
		if (obj instanceof XReturnStatement && ((XReturnStatement) obj).getValue() != null)
			obj = interpreter.evaluate(((XReturnStatement) obj).getValue(), context);
		if (obj instanceof VariableStorage)
			obj = ((VariableStorage) obj).getValue();
		return obj;
	}
}
